<template>
  <div>
    <el-card class="box-card">
      <div class="news_header">
        <MainSearchForm :formList="formList" :formValue="formValue" @formReset="formChange" @formSearch="formChange"></MainSearchForm>
        <el-button size="mini" type="primary" class="add-btn" @click="addNews">创建新闻</el-button>
      </div>
      <div class="main_table mg-t-20" style="min-height: 600px">
        <MainTable
          ref="orderTable"
          :loading="listLoading"
          :columns="newsColumns"
          :tableData="tableData"
          @selection-change="handleSelectionChange"
        >
          <template v-slot:status="{ row }">
            <span :style="{ color: row.status == 1 ? '#03A98E' : '#999999' }">{{ row.status == '1' ? '上线' : '下线' }}</span>
          </template>
          <template v-slot:cover="{ row }">
            <el-image
              style="width: 100%"
              :src="row.cover"
              :preview-src-list="[row.cover]"
              fit="cover"></el-image>
          </template>
          <template v-slot:time="{ row }">
            <div>
              <p v-if="row.start_time">开始时间：{{ row.start_time }}</p>
              <p v-if="row.start_time">到期时间：{{ row.end_time }}</p>
              <p v-if="!row.start_time">永久上线</p>
            </div>
          </template>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <MainLink color="#42BEAA" title="编辑" @linkClick="editNews(scope.row)"></MainLink>
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                v-if="scope.row.status == '1'"
                :title="scope.row.top === 1 ? '确定取消置顶吗？' : '确定置顶吗？'"
                @onConfirm="pinnedNews(scope.row)"
              >
                <MainLink slot="reference" color="#444444" :title="scope.row.top === 1 ? '取消置顶' : '置顶'"></MainLink>
              </el-popconfirm>
              <el-popconfirm
                confirm-button-text="是的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除吗？"
                @onConfirm="deleteNews(scope.row)"
              >
                <MainLink slot="reference" color="#F56C6C" title="删除"></MainLink>
              </el-popconfirm>
              <!-- <el-button
                type="primary"
                icon="el-icon-search"
                @click="viewNews(scope.row)"
                size="mini"
                title="查看"
              ></el-button> -->
            </template>
          </el-table-column>
        </MainTable>
      </div>

      <div class="footer_pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="page_sizes"
          layout=" ->,total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 查看新闻 -->
      <el-dialog
        :title="`${rowlist.title} `"
        :visible.sync="centerDialogVisible"
        width="50%"
        center
      >
        <div class="rowdialog">
          <div>
            <span> {{ rowlist.info }}</span>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="centerDialogVisible = false"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { Newsfromdata, delectfromdata, pinnedArticle} from "@/api/news/index";
import { getCategoryList } from "@/api/news/sort";
import Pagination from "../../mixins/pagination";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import MainTable from '@/components/MainTable/table.vue'
import { indexData } from './MockData'
const { newsColumns, formList, formValue } = indexData
export default {
  name: "news",
  components: {
    MainTable
  },
  mixins: [Pagination],
  data() {
    return {
      handleScrool: "",
      centerDialogVisible: false,
      rowlist: { author: "", id: 0, info: "", intro: "", status: 1, title: "" },
      formList,
      formValue,
      sendTime: [],
      tableData: [],
      currentPage: 1,
      // 勾选的数据
      multipleSelection: [],
      // 新闻日期
      pickerOptions: [],
      listLoading: false,
      dialogData:{
        title:"",
        status:false,
        mydata:{}
      },
      newsColumns
    };
  },
  activated() {
    this.fromdata();
    this.getCategory();
  },

  methods: {
    //  表单搜索
    formChange() {
      this.currentPage = 1
      this.page_sizes = 20
      this.fromdata()
    },
    //  获取分类列表
    getCategory() {
      const params = {
        page: this.currentPage,
        page_size: this.page_sizes,
        need_page: 0
      }
      getCategoryList(params).then(res => {
        this.formList[2].options = res.data.list.map(el => {
          return {
            label: el.name,
            value: el.id
          }
        })
      })
    },
    fromdata() {
      this.listLoading = true;
      let data = {
        page: this.currentPage,
        page_size: this.page_sizes,
        ...this.formValue
      };
      let query = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, data)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        data,
      );
      Newsfromdata(query).then(
        (res) => {
          this.listLoading = false;
          this.tableData = res.data.list;
          this.total = res.data.total;
        },
        (err) => {
          console.log(err);
        }
      );
    },
    //  置顶新闻
    pinnedNews(row) {
      pinnedArticle({ id: row.id, top: row.top === 1 ? 0 : 1 }).then(
        (res) => {
          if (res.errcode == 0) {
            this.$message.success(row.top === 1 ? "取消置顶成功" : '置顶成功');
            this.fromdata();
          } else {
            this.$message.error(res.errmsg);
          }
        },
        (err) => {
          console.log(err);
        }
      )
    },
    addNews() {
      this.$router.push("/news/add");
    },
    editNews(row) {
      // 修改新闻
      this.$router.push({
        path: "/news/add",
        query: {
          id: row.id
        }
      });
    },
    close(){
      this.dialogData.status=false;
      location.reload()
    },
    deleteNews(row) {
      // 删除新闻
      let query = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: row.id }
      );
      delectfromdata(query).then(
        (res) => {
          if (res.errcode == 0) {
            this.$message.success("删除成功");
            this.fromdata();
          } else {
            this.$message.error(res.errmsg);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    viewNews(row) {
      // 查看新闻
      // TODO: 实现查看逻辑
      this.centerDialogVisible = true;
      this.rowlist = row;
    },
    // 状态
    changeSwitch(e, row) {
      console.log("1", e, row);
    },

    // 勾选的数据
    handleSelectionChange(val) {
      console.log("val", val);
      this.multipleSelection = val;
    },

    // 底部到视口顶部的距离
    handleScroll() {
      const distance = window.innerHeight - 300;
      this.handleScrool = distance + "px";
      // console.log(this.handleScrool);
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.page_sizes = val;
      this.fromdata();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.fromdata();
    },
  },
  created() {
    this.handleScroll();
  },
};
</script>
<style lang="scss" scoped>
.box-card {
  width: 100%;
  margin: 0.875rem;
  .delectright {
    position: relative;
    left: 95%;
  }
}

.rowdialog {
  display: flex;
  justify-content: center;
  align-items: center;
}

.reset{
  background: none;
  color: #03A98E;
}
</style>
